# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools import float_is_zero


class MrpScrapWizard(models.TransientModel):
    _name = 'mrp.scrap.wizard'

    scrap_type=fields.Selection([
        ('1','原材料'),
        ('2', '产成品'),
    ],string=u'类型',default='1')
    @api.onchange('scrap_type')
    def onchange_scrap_type(self):
        production_id = self._context.get('default_production_id')
        self.production_id=production_id
        mo = self.env['mrp.production'].browse(production_id)
        if self.scrap_type=='1':

            products = mo.move_raw_ids.mapped('product_id')
        elif self.scrap_type=='2':
            products = mo.move_finished_ids.mapped('product_id')
        vals = []
        for p in products:
            vals.append([0, 0, {
                'product_id': p.id,
                'product_qty': 0,
            }])
        self.scrap_line_ids=False
        self.scrap_line_ids=vals


    def action_confirm_strap(self):
        valid_line= self.scrap_line_ids.filtered(lambda x: x.product_qty > 0)
        dest_location_id = self.env['stock.location'].search([('scrap_location', '=', True)], limit=1).id
        group_id=self.get_procurement_group()
        stock_move = self.env["stock.move"].with_context({})
        if self.scrap_type=='2':
            picking = self.create_picking(dest_location_id, group_id)
            for line in valid_line:
                if line.product_qty>line.max_scrap_qty:
                    raise UserError('报废数量不能大于可报废数量')
                vals = line.create_scarp_finish_move_vals(picking)
                move = stock_move.create(vals)
                move._action_confirm()
                move._action_assign()
                picking.action_assign()
                line.create_scarp_finish_product()
            return
        else:
            picking = self.create_picking(dest_location_id, group_id)
            for line in valid_line:
                if line.product_qty > line.max_scrap_qty:
                    raise UserError('报废数量不能大于可报废数量')
                vals = line.create_scarp_move_vals(picking)
                move = stock_move.create(vals)
                move._action_confirm()
                move._action_assign()
                picking.action_confirm()

    def create_picking(self, location_id, group):
        warehouse_id = self.production_id.picking_type_id.warehouse_id
        if not warehouse_id:
            raise UserError(u'该作业类型未设置对应仓库')

        picking_type=self.env['stock.picking.type'].search([('return_type','=','scrap_move')])

        if not picking_type:
            raise UserError(u'未找到报废调拨')
        pick = self.env['stock.picking'].search([('picking_type_id', '=', picking_type.id),
                                                 ('group_id', '=', group.id),
                                                 ('location_dest_id', '=', location_id)], limit=1)

        if not pick:
            vals = {
                'picking_type_id': picking_type.id,
                'group_id': group.id,
                'scarp_production_id': self.production_id.id,
                'date': fields.datetime.now(),
                'origin': u'报废 ' + self.production_id.name,
                'location_dest_id': picking_type.location_dest_id.id,
                'location_id':picking_type.location_id.id,
            }
            pick = self.env['stock.picking'].with_context({}).create(vals)
        return pick



    def get_procurement_group(self):
        name=self.production_id.name + u'-报废'
        group_id=self.env['procurement.group'].search([('name','=',name)],limit=1)
        if not  group_id:
            group_id=self.create_procurement_group()
        return group_id


    def create_procurement_group(self,name):
        return self.env['procurement.group'].create({
            'name': name
        })


    production_id = fields.Many2one(string=u'制造订单', comodel_name='mrp.production')
    scrap_line_ids = fields.One2many(string=u'报废明细', comodel_name='mrp.scrap.line.wizard', inverse_name='scrap_id')


    def create_picking(self, location_id, group):
        warehouse_id = self.production_id.picking_type_id.warehouse_id
        if not warehouse_id:
            raise UserError(u'该作业类型未设置对应仓库')
        picking_type = self.env["stock.picking.type"].search([('return_type', '=', 'stock_scrap')],
                                                             limit=1)
        if not picking_type:
            raise UserError(u'未找到对应的报废调拨类型')

        pick = self.env['stock.picking'].search([('picking_type_id', '=', picking_type.id),
                                                ('group_id', '=', group.id),
                                                ], limit=1)

        if not pick:
            vals = {
                'picking_type_id': picking_type.id,
                'group_id': group.id,
                # 'internal_picking_id': self.id,
                # 'partner_id': self.partner_id.id,
                'scarp_production_id': self.production_id.id,
                'date': fields.datetime.now(),
                'origin': u'报废 ' + self.production_id.name,
                'location_dest_id':location_id,
                'location_id': self.production_id.location_src_id.id,
            }
            pick = self.env['stock.picking'].with_context({}).create(vals)
        return pick

    def create_procurement_group(self):
        return self.env['procurement.group'].create({
            'name': self.production_id.name + u'-报废'
        })
class MrpScrapLineWizard(models.TransientModel):
    _name = 'mrp.scrap.line.wizard'

    scrap_id = fields.Many2one(string=u'报废单', comodel_name='mrp.scrap.wizard')
    product_id = fields.Many2one(string=u'产品', comodel_name='product.product')
    product_qty = fields.Float(string=u'数量')
    max_scrap_qty=fields.Float(string=u'最大可报废数量',compute='compute_max_scrap_qty')

    def compute_max_scrap_qty(self):
        for record in self:
            consume_line_id = record.scrap_id.production_id.consume_line_ids.filtered(
                lambda x: x.product_id == record.product_id)
            if consume_line_id:
                record.max_scrap_qty=consume_line_id.can_scrap_qty
            else:
                main_product_moves = record.scrap_id.production_id.move_finished_ids.filtered(
                    lambda x: x.product_id.id == record.product_id.id)

                quantity_done = sum(main_product_moves.mapped('quantity_done'))
                record.max_scrap_qty=record.scrap_id.production_id.product_qty-quantity_done



    def create_scarp_finish_move_vals(self,picking):
        dest_location_id = self.env['stock.location'].search([('scrap_location', '=', True)], limit=1).id
        location_id=self.env['stock.location'].search([('usage','=','production')],limit=1).id
        self.ensure_one()
        return {
            'name': self.scrap_id.production_id.name + u' 报废 ' + self.product_id.name,
            'product_id': self.product_id.id,
            'product_uom': self.product_id.uom_id.id,
            'date':  fields.datetime.now(),
            'picking_id':picking.id,
            'date_expected':  fields.datetime.now(),
            'location_id': location_id,
            'location_dest_id': dest_location_id,
            'state': 'draft',
            'origin': self.scrap_id.production_id.name,
            'warehouse_id': self.scrap_id.production_id.picking_type_id.warehouse_id.id,
            'product_uom_qty': self.product_qty,
            'scarp_production_id': self.scrap_id.production_id.id,
        }
    def create_scarp_finish_product(self):
        # 报废产成品的同时，把原材料同配比从产线到虚拟生产
        location_id=self.scrap_id.production_id.location_src_id.id#领料区

        dest_location_id = self.env['stock.location'].search([('usage', '=', 'production')], limit=1).id#产线
        for line in self.scrap_id.production_id.bom_id.bom_line_ids:
            vals={
                'name': self.scrap_id.production_id.name + u' 报废 ' + line.product_id.name,
                'product_id': line.product_id.id,
                'product_uom': line.product_id.uom_id.id,
                'date': fields.datetime.now(),
                'date_expected': fields.datetime.now(),
                'location_id': location_id,
                'location_dest_id': dest_location_id,
                'state': 'draft',
                'origin':  self.scrap_id.production_id.name + u' 报废 ' + self.product_id.name,
                'warehouse_id': self.scrap_id.production_id.picking_type_id.warehouse_id.id,
                'product_uom_qty': self.product_qty*line.product_qty/line.bom_id.product_qty,
                'quantity_done':self.product_qty*line.product_qty/line.bom_id.product_qty,
                'scarp_production_id': self.scrap_id.production_id.id,
            }
            move_id=self.env['stock.move'].create(vals)
            move_id._action_done()
    def create_scarp_move_vals(self, picking):

        self.ensure_one()
        return {
            'name': self.scrap_id.production_id.name + u' 报废 ' + self.product_id.name,
            'product_id': self.product_id.id,
            'product_uom': self.product_id.uom_id.id,
            'date': picking.date,
            'date_expected': picking.date,
            'location_id': picking.location_id.id,
            'location_dest_id': picking.location_dest_id.id,
            'picking_id': picking.id,
            'state': 'draft',
            'quantity_done':self.product_qty,
            'picking_type_id': picking.picking_type_id.id,
            'origin': picking.name,
            'warehouse_id': picking.picking_type_id.warehouse_id.id,
            'product_uom_qty': self.product_qty,
            'scarp_production_id': self.scrap_id.production_id.id,
        }